import { Context } from "@midwayjs/koa";
import IP2Region from "ip2region";

/**
 * 地址解析类
 * 
 * @author jn
 */
export class ServletUtils {

    /**
     * 获取ip地址
     * @param ctx ctx
     * @returns 
     */
    static getRequest(ctx: Context) {
        let ipv4 = this.ipv6ToV4(this.getClientIp(ctx.request));
        return ipv4;
    }

    /**
     * 获取真实地址
     * @param ctx ctx
     * @returns 
     */
    static getAddress(ctx: Context) {
        let ipv4 = this.ipv6ToV4(this.getClientIp(ctx.request));
        const query = new IP2Region();
        return JSON.parse(JSON.stringify(query.searchRaw(ipv4)).replace(" ", ""));
    }

    /**
     * 获取ip地址
     * @param req ctx
     * @returns 
     */
    static getClientIp(req: any) {
        return req.headers["x-forwarded-for"] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress ||
            ""
    }

    /**
     * 转ip
     * @param ip IP地址
     * @returns 
     */
    static ipv6ToV4(ip: string) {
        if (ip.split(",").length > 0) {
            ip = ip.split(",")[0]
        }
        ip = ip.substr(ip.lastIndexOf(":") + 1, ip.length);
        return ip;
    }

}